package snsdbook.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.SQLUtil;
import util.Util;

/**
 * Servlet implementation class Comment
 */
public class CommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CommentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
  
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  String type = request.getParameter("type");
	  
	  String query = null;
	  boolean is_query = false;
	  if (type.equals("getusername")) {
	    String id = request.getParameter("id");
	    query = "SELECT komentator FROM komentar WHERE id_komentar='" + id + "'";
	    is_query = true;
	  } else if (type.equals("getcontent")) {
	    String id = request.getParameter("id");
      query = "SELECT isi_komentar FROM komentar WHERE id_komentar='" + id + "'";	    
      is_query = true;
	  } else if (type.equals("gettimestamp")) {
	    String id = request.getParameter("id");
      query = "SELECT waktu FROM komentar WHERE id_komentar='" + id + "'";
      is_query = true;
	  } else if (type.equals("getcommentids")) {
	    String id = request.getParameter("id");
      query = "SELECT id_komentar FROM komentar WHERE id_berita='" + id + "' " +
              "ORDER BY waktu DESC";
      is_query = true;
	  } else if (type.equals("insert")) {
	    String username = request.getParameter("username");
	    String content = request.getParameter("content");
	    String id = request.getParameter("id");
	    query = "INSERT INTO komentar(komentator, nama_komentar, isi_komentar, id_berita, waktu)" +
	            " VALUES('" + username + "','" + username +
	            "','" + content + "','" + id + "','" +
	            System.currentTimeMillis() + "')";
	  } else if (type.equals("delete")) {
	    String id = request.getParameter("id");
	    query = "DELETE FROM komentar " +
              "WHERE id_komentar='" + id + "'";
	  }
	  
	  if (is_query) {
	    String[] result = SQLUtil.Query(query);
	    StringBuilder output = new StringBuilder();
	    for (String str : result) {
	      if (output.length() > 0) {
	        output.append(",");
	      }
	      output.append(str);
	    }
	    
	    // System.out.println(response + " is output");
	    Util.PrintAndClose(response, output.toString());
	    return;
	  } else {
	    SQLUtil.Modify(query);
	  }
	}

}
